/*
 * @Author: nengwu 409791297@qq.com
 * @Date: 2020-06-25 10:20:03
 * @LastEditors: mylesshie@gmail.com
 * @LastEditTime: 2020-09-13 21:44:24
 * @description:
 */

import React, { useCallback, useState, useEffect } from 'react'
import { StatusBar, FlatList, SafeAreaView } from 'react-native'
import { useDispatch } from 'react-redux'

import LiveItem from '@/components/LiveItem'
import HomeHeader from '@/components/HomeHeader'
import EmptyList from '@/components/EmptyList'
import * as activityActions from '@/actions/activity'
import styles from './styles'

const Live = props => {
  const dispatch = useDispatch()
  const [liveList, setLiveList] = useState([])
  const [pageNum, setPageNum] = useState(1)
  const [pageEnd, setPageEnd] = useState(false)
  const [isRefreshing, setIsRefreshing] = useState(false)
  const pageSize = 20

  const getList = useCallback(() => {
    dispatch(activityActions.getLiveList(pageNum, pageSize)).then(res => {
      setIsRefreshing(false)
      if (pageNum === 1) {
        setLiveList(res.list)
      } else {
        setLiveList(liveList.concat(res.list))
      }
      setPageEnd(res.total <= res.pageNum * res.pageSize)
    })
  }, [dispatch])

  useEffect(() => {
    getList()
  }, [pageNum, pageSize])

  const _onRefresh = () => {
    setPageNum(1)
    setIsRefreshing(true)
    getList()
  }

  const _onLoadMore = () => {
    if (pageEnd) return
    setPageNum(pageNum + 1)
  }

  const _renderItem = ({ item }) => {
    return (
      <LiveItem
        viewCount={item.viewCount}
        videoTitle={item.videoTitle}
        videoUrl={item.viedoUrl}
        coverUrl={item.coverUrl}
        createdTime={item.createdTime}
      />
    )
  }

  const _search = text => {
    dispatch(activityActions.doSearch(text)).then(res => {
      setLiveList(res)
    })
  }

  return (
    <>
      <StatusBar
        barStyle="dark-content"
        backgroundColor="#f14047"
        translucent={false}
      />
      <HomeHeader doSearch={_search} />
      <SafeAreaView style={styles.wrap}>
        <FlatList
          data={liveList}
          renderItem={_renderItem}
          onRefresh={_onRefresh}
          refreshing={isRefreshing}
          onEndReached={_onLoadMore}
          onEndReachedThreshold={0.3}
          keyExtractor={item => item.createdTime}
          ListEmptyComponent={<EmptyList />}
        />
      </SafeAreaView>
    </>
  )
}

export default Live
